﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace aboveXWords.GUI
{
  [Serializable]
  public class Word : Squares
  {
    public Word(IEnumerable<Square> squares)
    {
      foreach (Square square in squares)
      {
        var letter = square as Letter;
        Add(letter != null ? new Letter(letter) : new Letter(square));
      }
      // We need two sort the squares
      Sort(
        (a, b) =>
        (int) ((a.Rectangle.X == b.Rectangle.X) ? a.Rectangle.Y - b.Rectangle.Y : a.Rectangle.X - b.Rectangle.X));
    }

    public override bool Select
    {
      set
      {
        base.Select = value;
        foreach (Square square in this)
          square.Cursor = false;
      }
    }

    public Square Cursor
    {
      get
      {
        for (int square = 0; square < Count; ++square)
        {
          if (!this[square].Cursor) continue;
          ++square;
          if (square != Count)
          {
            this[square].Cursor = true;
            this[square - 1].Cursor = false;
          }
          return this[square - 1];
        }
        if (Count < 2) return null;
        if (Count > 2) this[2].Cursor = true;
        return this[1];
      }
    }

    /// <summary>
    /// 
    /// </summary>
    public void Bend(Square square)
    {
      for (int s = 0; s < Count - 1; ++s)
      {
        if (!this[s].Equals(square)) continue;
        if (this[s].Rectangle.Y == this[s + 1].Rectangle.Y)
        {
          for (++s; s < Count; ++s)
            this[s].Rectangle = new RectangleF(
              this[s - 1].Rectangle.Location.X,
              this[s - 1].Rectangle.Location.Y + this[s - 1].Rectangle.Height,
              this[s - 1].Rectangle.Width,
              this[s - 1].Rectangle.Height);
        }
        else
        {
          for (++s; s < Count; ++s)
            this[s].Rectangle = new RectangleF(
              this[s - 1].Rectangle.Location.X + this[s - 1].Rectangle.Width,
              this[s - 1].Rectangle.Location.Y,
              this[s - 1].Rectangle.Width,
              this[s - 1].Rectangle.Height);
        }
        break;
      }
    }
  }
}